package wechat;


import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class RestTemplateUtils {

    private static RestTemplate restTemplate = new RestTemplate();


    /***
     * post  Request 参数封装
     * @param urlStr
     * @param param
     * @return
     */
    public static Map postRequest(String urlStr, MultiValueMap<String, String> param) {
        String url = urlStr;
        Map<String, Object> map = new HashMap();

        //请求数据
        try {
            String str = restTemplate.postForObject(url, param, String.class);
            JSONObject json = JSONObject.parseObject(str);
//            {"msg":"返回成功","errno":"200","data":{}}
            if (json.get("errno").equals("200")) {
                map.put("errno", (String) json.get("errno"));
                map.put("data", json.get("data"));
            } else {
                map.put("errno", (String) json.get("errno"));
                map.put("msg", (String) json.get("msg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("errno", "201");
            map.put("msg", "调用异常");
            return map;

        }
        return map;

    }

    /***
     * post 实体参数请求
     * @param urlStr
     * @param object
     */
    public static Map<String, Object> postEntity(String urlStr, Object object) {
        String url =  urlStr;
        Map<String, Object> map = new HashMap();
        //请求数据
        try {
            ResponseEntity<String> str = restTemplate.postForEntity(url, object, String.class);
            if ((HttpStatus.OK.value() == str.getStatusCode().value())) {
                JSONObject json = JSONObject.parseObject(str.getBody());
                if (json.get("errno").equals("200")) {
                    map.put("errno", (String) json.get("errno"));
                    map.put("data", json.get("data"));
                } else {
                    map.put("errno", (String) json.get("errno"));
                    map.put("msg", json.get("msg"));
                }
            } else {
                map.put("errno", str.getStatusCode().value() + "");
                map.put("data", "接口请求异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("errno", "201");
            map.put("msg", "调用异常");
            return map;

        }
        return map;
    }

}

